<?php 
/*提交订单*/

	include('../conn.php');
	include("../common.php");
	// $_REQUEST['usersFirstId'] = '2591';
	// 生成订单号函数
	function build_order_no(){
	    return date('Ymd') . str_pad(mt_rand(1, 99999), 8, '0', STR_PAD_LEFT);
	}
  
	/*解密*/
	//$z = $_REQUEST['z'];
	//$param = decrypt($z);
	//$paramArr = getArr($param);

	/*所有商家、发票、购物券、留言，运费险
		order_shop_data :{shopid:{
			invoiceid:'发票id',
			couponid :'购物券id',
			fan_juan_id:'返卷id',
			msg:'给厂商的留言',
			isbuyFreightRisk:'是否购买了运费险0没购买，1购买',
		}}
	 */
	$order_shop_data = $_REQUEST['order_shop_data'];
	//$order_shop_data = $paramArr['c'];
	/*order_invoice_data = {shopid:{type:'0电子发票,1增值发票',data:{type:'1个人,2单位',name:'名称,content:'内容''},data:{invoice_id:'增值发票id'}}}
	*/
	$order_invoice_data = $_REQUEST['order_invoice_data'];
	//$order_invoice_data = $paramArr['e'];
	//收货地址id
	$addressid = $_REQUEST['addressid'];
	//$addressid = $paramArr['b'];
	//用户id
	$userid = $_REQUEST['userid'];
	//$userid = $paramArr['a'];
	//是否从购物车购买，1是，0不是
	$is_car_purchase = $_REQUEST['is_car_purchase'];
	//$is_car_purchase = $paramArr['g'];
	//是否使用返卷,1使用,0是不使用
	$use_return_volume = (int)$_REQUEST['use_return_volume'];
	//$use_return_volume = $paramArr['f'];
	if($use_return_volume){
		$use_return_volume = 1;
	}

	//返卷剩余的钱
	$return_volume_price = 0;

	//返回数据
	$result_data_array = array();

	if(!$order_shop_data){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少店铺信息';
		echo json_encode($result_data_array);
		exit;
	}


	if(!$addressid ){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少收货地址';
		echo json_encode($result_data_array);
		exit;
	}

	if(!$userid){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '缺少用户信息';
		echo json_encode($result_data_array);
		exit;
	}

	$order_shop_data = json_decode($order_shop_data,true);
	if(!$order_shop_data){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '店铺信息格式错误';
		echo json_encode($result_data_array);
		exit;

	}

	

	$order_invoice_data = json_decode($order_invoice_data,true);
	if(!is_array($order_invoice_data)){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '发票信息格式错误';
		echo json_encode($result_data_array);
		exit;

	}
	if($is_car_purchase == null || $is_car_purchase == ''){
		$result_data_array['code'] =  -100;
		$result_data_array['msg'] = '订单异常';
		echo json_encode($result_data_array);
		exit;

	}

	// 查找送货地址
	$query = '';
	if ($addressid != '') {
		$query = mysql_query("select * from address where id=".$addressid);
	}else{
		// 默认地址
		$query = mysql_query("select * from address where userid=".$userid." and state = 1");
		// 默认地址 end
	}
	$user_query = mysql_query('select return_volume from user where userid = '.$userid);
	$user_result = mysql_fetch_assoc($user_query);
	if(!$user_result){
		$result_data_array['code'] = -100;
		$result_data_array['msg'] = '用户信息异常';
		echo json_encode($resultArray);
		exit;

	}
	$return_volume_price = $user_result['return_volume']+0;
	$myaddress = mysql_fetch_assoc($query);

	if(!$myaddress){
		$result_data_array['code'] = -100;
		$result_data_array['msg'] = '没有查询到收货地址';
		echo json_encode($result_data_array);
		exit;
	}

	//查询所有购物车商品
	$all_car_goods = array();

	//购物车
	if($is_car_purchase == 1){
		/*
			购买数量,id
			order_goods_car_num:{carid:'购买数量'}
		*/
		$order_goods_car_num = $_REQUEST['order_goods_car_num'];
		//$order_goods_car_num = $paramArr['d'];
		$order_goods_car_num = json_decode($order_goods_car_num,true);

		if(!$order_goods_car_num){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '商品信息格式错误101';
			echo json_encode($result_data_array);
			exit;

		}

		//所有购物车id
		$carids = implode(',',array_keys($order_goods_car_num));

		//查询购物车商品信息
		$car_sql = "select "
			."a.carid,a.goodsid,a.shopid,a.fTitle,a.price as car_price,a.sTitle,a.number as car_number"
			.",b.start_num,b.shangjia, b.number as goods_number, b.price as goods_price,b.title,b.muid,b.zixilie,b.istuangou,b.buygroup_id"
			.",c.name,c.open,c.check,c.rates "
			." from car as a "
			." left join goods as b on b.goodsid = a.goodsid "
			." left join shop as c on c.shopid = a.shopid "
			." where  (a.state = 0 or a.state = 3) and a.carid in (".$carids.")";

		$car_query = mysql_query($car_sql);

		if(mysql_num_rows($car_query) == 0){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '订单异常001';
			echo json_encode($result_data_array);
			exit;
		}

		while ($car_row = mysql_fetch_assoc($car_query)){
			
			if(!(int)$car_row['check']){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '店铺:'.$car_row['name'].'未通过审核，无法购买';
				echo json_encode($result_data_array);
				exit;
			}
			if(!(int)$car_row['open']){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '店铺:'.$car_row['name'].'已关业，无法购买';
				echo json_encode($result_data_array);
				exit;
			}
			if(!(int)$car_row['shangjia']){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '商品:'.$car_row['title'].'已下架，无法购买';
				echo json_encode($result_data_array);
				exit;

			}

			$fTitle = $car_row['fTitle'];
			$sTitle = $car_row['sTitle'];

			if( $fTitle  != null && $fTitle != ''){
				$goodsselect_sql = "select price,number from goodsselect where goodsid = ".$car_row['goodsid']." and fTitle = '".$fTitle."'";
				if($sTitle != null && $sTitle != ''){
					$goodsselect_sql .= " and sTitle = '".$sTitle."'";
				}
				$goodsselect_query = mysql_query($goodsselect_sql);
				$goodsselect_row = mysql_fetch_assoc($goodsselect_query);
				if($goodsselect_row){
					$car_row['goods_price'] = $goodsselect_row['price'];
					$car_row['goods_number'] = $goodsselect_row['number'];
				}else{
					$result_data_array['code'] =  -100;
					$result_data_array['msg'] = '商品:'.$car_row['title'].'规格已下架，无法购买';
					echo json_encode($result_data_array);
					exit;
				}

			}
			//购买的数量
			$addnum = $order_goods_car_num[$car_row['carid']]+0;

			if($addnum<1 || $addnum < $car_row['start_num']+0){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '非法操作';
				echo json_encode($result_data_array);
				exit;
			}

			//判断库存量
			if($car_row['goods_number']+0 <  $car_row['addnum']){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '商品:'.$car_row['title'].'库存量不足，无法购买';
				echo json_encode($result_data_array);
				exit;

			}
			$usersFirstId = $order_shop_data[$car_row['shopid']]['usersFirstId'];
			//var_dump($order_shop_data[$car_row['shopid']]);
			//计算首单返券
			if($usersFirstId) {
				$car_row['first_price'] = get_car_fPrice($car_row['goodsid'], $car_row['goods_price'], $usersFirstId, $addnum, $userid);
			}
			
			$car_row['goods_price'] += 0;//商品单价
			$istuangou = $car_row['istuangou'];
			if($istuangou == 1){
				$buyg = mysql_query("select mcount,money from buygroup where buygroup_id=".$car_row['buygroup_id']."");
	        	$buyone = mysql_fetch_assoc($buyg);
	        	$car_row['goods_price'] = round($buyone['money']*100/$buyone['mcount'])/100;
			}
			$car_row['goods_total_price'] = round($car_row['goods_price']*100*$addnum)/100;//总价=单价*数量,精确到两位小数点
			$car_row['addnum'] = $addnum;//购买数量
			$car_row['express_price'] = getTotal_express_price($myaddress,$car_row,$addnum);//快递费
			$car_row['freightRisk'] = 0;
			
			// echo $car_row['goods_total_price'] . ',';
			if($order_shop_data[$car_row['shopid']]['isbuyFreightRisk'] == 1){
				$car_row['freightRisk'] = getTotal_Freight($addnum);//运费险

			}
			
			$all_car_goods[$car_row['shopid']]['rates'] = $car_row['rates'];
			if(!$all_car_goods[$car_row['shopid']]){
				$all_car_goods[$car_row['shopid']] = array('goods_list'=>array());
			}

			$all_car_goods[$car_row['shopid']]['goods_list'][] = $car_row;
		}

		foreach ($all_car_goods as $shopid => $car_goods) {
			$rates = $car_goods['rates']+0;
			//订单号
			$order_numbers = build_order_no();

			//一个订单总价格
			$order_total_price = 0;

			//首单返券优惠金额
			$first_price = 0;

			//一个订单总快递费
			$order_total_express_price = 0;

			//一个订单总的运费险
			$order_total_freightRisk_price = 0;
			
			//返卷金额
			$fan_juan_price = 0;
			$fan_juan_bi_li = 0;
			foreach ($car_goods['goods_list'] as $key => $goods_item) {
				//精确到4位小数点
				$fan_juan_array = calculation_rate($goods_item['goodsid'],$goods_item['goods_total_price']);
				$fan_juan_price += $fan_juan_array[0];
				$fan_juan_bi_li = $fan_juan_array[1];
				$first_price += $goods_item['first_price'];

				$order_total_price = round($order_total_price*100 + $goods_item['goods_total_price']*100)/100 - $goods_item['first_price'];

				$order_total_express_price = round($order_total_express_price*100 + $goods_item['express_price']*100)/100;
				$order_total_freightRisk_price = round($order_total_freightRisk_price*100 + $goods_item['freightRisk']*100)/100;

			}
			/*----------------------------------------*/
			//返佣金额
			$fan_yong_price =  round($rates * $order_total_price)/100; 
			//如果返佣金额小于一分钱
			if($fan_yong_price < 0.01 && $rates > 0){
				$fan_yong_price = 0.01;
			}
			$all_car_goods[$shopid]['fan_yong_price'] = $fan_yong_price;

			if($fan_juan_price < 0.01 && $fan_juan_price != 0){
				$fan_juan_price = 0.01;
			}
			$all_car_goods[$shopid]['fan_juan_price'] = $fan_juan_price;
						
			/*----------------------------------------*/
			$all_car_goods[$shopid]['first_price'] = $first_price;
			$all_car_goods[$shopid]['usersFirstId'] = $usersFirstId;
			$all_car_goods[$shopid]['rates'] = $rates;
			$all_car_goods[$shopid]['rate'] = $fan_juan_bi_li;
			$all_car_goods[$shopid]['order_total_price'] = $order_total_price;//订单总价

			$all_car_goods[$shopid]['order_total_express_price'] = $order_total_express_price;//订单总快递费
			$all_car_goods[$shopid]['order_isbuyFreightRisk'] = $order_shop_data[$shopid]['isbuyFreightRisk'];//是否购买运费险
			$all_car_goods[$shopid]['order_total_freightRisk_price'] = $order_total_freightRisk_price;//订单总运费险
			$all_car_goods[$shopid]['order_coupon_price'] = 0; //优惠券总价


			//优惠券id，不适用则null
			$couponid = $order_shop_data[$shopid]['couponid'];
			$all_car_goods[$shopid]['order_couponid'] = $couponid;

			$all_car_goods[$shopid]['msg'] = $order_shop_data[$shopid]['msg'];

			if($couponid){
				//使用的优惠券id
				$all_car_goods[$shopid]['order_coupon_price'] = get_coupon_price($couponid,$order_total_price,$userid);
			}

			//是否使用返卷，0为不适用，1使用,如果返卷余额已经没了，就不使用
			$all_car_goods[$shopid]['order_use_return_volume'] = $return_volume_price>0?$use_return_volume:0;
			$all_car_goods[$shopid]['order_return_volume_price'] = 0;
			// 如果使用返卷
			if($use_return_volume == 1 && $return_volume_price > 0){

				// 如果返卷余额大于等于商品总价
				if($return_volume_price >= $all_car_goods[$shopid]['order_total_price']){
					$all_car_goods[$shopid]['order_return_volume_price'] = $all_car_goods[$shopid]['order_total_price'];
					$return_volume_price -= $all_car_goods[$shopid]['order_total_price'];

				// 如果返卷余额小于商品总价
				}else{
					$all_car_goods[$shopid]['order_return_volume_price'] = $return_volume_price;
					$return_volume_price = 0;
				}


			}
			// $all_car_goods[$shopid]['first_coupon'] = $all_car_goods[$shopid]['order_total_price'] + 10;
			//应结算金额 + $all_car_goods[$shopid]['order_return_volume_price']*100
			$ying_jie_price = round($order_total_price*100 - $fan_juan_price*100 - $fan_yong_price*100 - $all_car_goods[$shopid]['order_coupon_price']*100 + $order_total_express_price*100 - $first_price*100)/100;
			
			$all_car_goods[$shopid]['ying_jie_price'] = $ying_jie_price;
			

			//发票信息
			$invoice_data = $order_invoice_data[$shopid];

			$invoice_type = 0;
			if($invoice_data){
				$invoice_type = (int)$invoice_data['type'];
				$all_car_goods[$shopid]['invoice_data']= mysql_escape_string(json_encode($invoice_data['data']));
			}
			$all_car_goods[$shopid]['invoice_type'] = $invoice_type;
		}

		
	    generateOrders($all_car_goods,$userid,$myaddress,$return_volume_price);



	} else {
		//order_goods_data:{goodsid:'',addnum:'购买数量',fTitle:'',sTitle:''}
		$order_goods_data = $_REQUEST['order_goods_data'];
		//$order_goods_data = $paramArr['j'];
		$order_goods_data = json_decode($order_goods_data,true);
		if(!$order_goods_data){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '商品信息格式错误100';
			echo json_encode($result_data_array);
			exit;
		}

		if(!$order_goods_data['goodsid']){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '商品信息格式错误1001';
			echo json_encode($result_data_array);
			exit;

		}
		if(!$order_goods_data['addnum']){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '商品信息格式错误1002';
			echo json_encode($result_data_array);
			exit;

		}
		
		$goodsid = $order_goods_data['goodsid'];
		$addnum = $order_goods_data['addnum'];
		$fTitle = $order_goods_data['fTitle'];
		$sTitle = $order_goods_data['sTitle'];
		$price = 0;

		$sql = "select ";
		$sql.= "a.shopid,a.start_num,a.shangjia, a.number as goods_number, a.price as goods_price,a.title,a.muid,a.zixilie,a.istuangou,a.buygroup_id";
		$sql.= " ,c.name,c.open,c.check ,c.rates";
		$sql.=" from goods as a left join shop as c on c.shopid = a.shopid  where a.goodsid = " . $goodsid;
		
		$goods_query = mysql_query($sql);
		$goods_result = mysql_fetch_assoc($goods_query);
		if(!$goods_result){
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '该商品已经下架';
			echo json_encode($result_data_array);
			exit;

		}
		$rates = $goods_result['rates']+0;
        $query = mysql_query("select htservice,kgservice,distribution_fee,kefuid,iscanlian from shop where shopid=".$goods_result[shopid]);

        $shop = mysql_fetch_assoc($query);



		$htservice = explode(',', $shop[htservice]);
		$htlen = count($htservice);
		$services = array();
		$yijian = false;
		for ($i=0; $i < $htlen; $i++) { 
			if($htservice[$i] == '9'){
                 $yijian=true;
			}
			
		}
		if(!$yijian){
			if($addnum < $goods_result['start_num']+0){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '起批量'.$goods_result['start_num'].'件';
				echo json_encode($result_data_array);
				exit;

			}
	    }
		if($fTitle){
			$goodsselect_query = mysql_query('select price from goodsselect where number > 0 and goodsid='.$goodsid.' and fTitle = "'.$fTitle.($sTitle?'" and sTitle = "'.$sTitle.'"':'"'));
			$goodsselect_result = mysql_fetch_assoc($goodsselect_query);
			if(!$goodsselect_result){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '该商品已经下架或者已无库存';
				echo json_encode($result_data_array);
				exit;

			}
			$goods_result['goods_price'] = $goodsselect_result['price'];
		}


        $istuangou = $goods_result['istuangou'];
        if($istuangou == 1){
        	$buyg = mysql_query("select mcount,money from buygroup where buygroup_id=".$goods_result['buygroup_id']."");
        	$buyone = mysql_fetch_assoc($buyg);
        	$goods_result['goods_price'] = round($buyone['money']*100/$buyone['mcount'])/100;
        }
		$shopid = $goods_result['shopid'];
		$goods_result['addnum'] = $addnum;
		//总价=单价*数量,精确到两位小数点
		$goods_result['goods_total_price'] = round($goods_result['goods_price']*100 *$addnum)/100;
		$goods_result['addnum'] = $addnum;//购买数量
		$goods_result['express_price'] = getTotal_express_price($myaddress,$goods_result,$addnum);//快递费
		$goods_result['freightRisk'] = 0;
		$goods_result['order_isbuyFreightRisk'] = $order_shop_data[$shopid]['isbuyFreightRisk'];

		if($order_shop_data[$shopid]['isbuyFreightRisk'] == 1){
			$goods_result['freightRisk'] = getTotal_Freight($addnum);//运费险
		}

		
		//优惠券id，不用则null
		$couponid = $order_shop_data[$shopid]['couponid'];
		$goods_result['order_couponid'] = $couponid;

		$goods_result['msg'] = $order_shop_data[$shopid]['msg'];

		if($couponid){
			//使用的优惠券id
			$goods_result['order_coupon_price'] = get_coupon_price($couponid,$goods_result['goods_total_price'],$userid);
		}

		//是否使用返卷，0为不适用，1使用,如果返卷余额已经没了，就不使用
		$goods_result['order_use_return_volume'] = $return_volume_price>0?$use_return_volume:0;
		$goods_result['order_return_volume_price'] = 0;
		// 如果使用返卷
		if($use_return_volume == 1 && $return_volume_price > 0){

			// 如果返卷余额大于等于商品总价
			if($return_volume_price >= $goods_result['goods_total_price']){
				$goods_result['order_return_volume_price'] = $all_car_goods[$shopid]['goods_total_price'];
				$return_volume_price -= $all_car_goods[$shopid]['goods_total_price'];

			// 如果返卷余额小于商品总价
			}else{
				$goods_result['order_return_volume_price'] = $return_volume_price;
				$return_volume_price = 0;
			}
		}
		//记录剩余的返卷
		$user_return_volume_price = $return_volume_price;

		//发票信息
		$invoice_data = $order_invoice_data[$shopid];

		$invoice_type = 0;
		if($invoice_data){
			$invoice_type = (int)$invoice_data['type'];
			$goods_result['invoice_data']= mysql_escape_string(json_encode($invoice_data['data']));
		}
		$goods_result['invoice_type'] = $invoice_type;

		$all_order_total_goods_price = 0;
		mysql_query("BEGIN");
		//收货地址
		$address =  $myaddress['province'].",".$myaddress['city'].",".$myaddress['quyu'].",".$myaddress['address'].",".$myaddress['name'].",".$myaddress['tel'];
		//订单状态
		$state = 0;

		//单个订单号
		$order_numbers = build_order_no();
		//订单商品总价
		$totalprice = $goods_result['goods_total_price'];
		//是否购买运费险
		$buyFreightRisk = $goods_result['order_isbuyFreightRisk'];
		//运费险总价
		$freightRisk_price = $goods_result['freightRisk'];
		//快递费总价
		$distribution_fee = $goods_result['express_price'];
		//留言
		$msg = $goods_result['msg'];
		//使用的优惠券价值
		$coupon_price = $goods_result['order_coupon_price'];
		//使用的优惠券id
		$coupon_id = $goods_result['order_couponid'];
		var_dump($couponid);
		//是否使用返卷
		$use_return_volume = $goods_result['order_use_return_volume'];
		//是否使用返卷价值
		$return_volume_price = $goods_result['order_return_volume_price'];

		//发票类型
		$invoice_type = $goods_result['invoice_type'];
		//发票信息数据
		$invoice_data = $goods_result['invoice_data'];
		//下单时间
		$xia_dan_datetime = date("Y-m-d H:i:s");
		//返佣金额
		$fan_yong_price =  round($rates * $totalprice)/100; 
		//如果返佣金额小于一分钱
		if($fan_yong_price < 0.01 && $rates > 0){
			$fan_yong_price = 0.01;
		}

		$fan_juan_array = get_rate($goodsid,$totalprice);
		//返卷金额
		$fan_juan_price = $fan_juan_array[0];
		$fan_juan_bi_li = $fan_juan_array[1];
		$usersFirstId = json_decode($_GET['order_shop_data'],true);
		$usersFirstId = $usersFirstId[$goods_result['shopid']]['usersFirstId'];
		//首单返券金额
		$first_coupon_price = get_car_fPrice($goodsid, $goods_result['goods_price'], $usersFirstId, $addnum, $_GET['userid']);
		
		//应结算金额+ $return_volume_price*100
		$ying_jie_price = ($totalprice*100 - $fan_juan_price*100 - $fan_yong_price* 100 - $coupon_price* 100  + $distribution_fee*100 - $first_coupon_price*100)/100;
/*		$usersFirstId = '2591';
		if($usersFirstId) {
			$query = mysql_query("SELECT * FROM orders_users_first WHERE id = " . $usersFirstId);
			$usersFirst = mysql_fetch_assoc($query);
			$firstConpon = $usersFirst['amount']*($usersFirst['first_cate_use']*0.01);
			$totalprice -= $firstConpon;
			$usersFirst['lastAmount'] -= $firstConpon;
			$sql = "UPDATE orders_users_first set amount = " . $usersFirst['amount'] . " AND lastAmount = " . $usersFirst['lastAmount'] . " WHERE id = " . $usersFirstId;
			$query = mysql_query($sql);
		}*/
		//应付金额
		$all_order_total_goods_price = round( $distribution_fee*100 + $freightRisk_price*100 + $totalprice*100 - $coupon_price*100 - $return_volume_price*100)/100;
		//end 
		
		$orders_id = insert_order_data(null, $order_numbers, $totalprice, $state, $userid, $address, $shopid, 
		$freightRisk_price, $buyFreightRisk, $distribution_fee, $msg, $coupon_price,$coupon_id, $_REQUEST['usersFirstId'], $first_coupon_price, $xia_dan_datetime, $invoice_type,$invoice_data,$return_volume_price,$fan_juan_price,$fan_yong_price,$ying_jie_price,$fan_juan_bi_li,$rates, $all_order_total_goods_price);



		if(!$orders_id){
			mysql_query("ROLLBACK");
			mysql_query("END");

			$result_data_array['code'] =  -101;
			$result_data_array['msg'] = '下单失败01';
			echo json_encode($result_data_array);
			exit;
		}

		//更新优惠券
		if( $coupon_id != 0){
			$update_mycoupon_query = mysql_query('update mycoupon set is_use = 1 where id = '.$coupon_id);
			if(!$update_mycoupon_query ){
				mysql_query("ROLLBACK");  
				mysql_query("END");
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '提交订单失败3';
				echo json_encode($result_data_array);
				exit;
			}

		}

		//更新用户返卷金额
		$update_user_return_volume_query = mysql_query('update user set return_volume = '.$user_return_volume_price.' where userid = '.$userid);
		if(!$update_user_return_volume_query ){
			mysql_query("ROLLBACK");  
			mysql_query("END");
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '提交订单失败4';
			echo json_encode($result_data_array);
			exit;
		}
		
		// 记录到购物车
		$srats = mysql_query("INSERT INTO car(userid,goodsid,goodsname,fTitle,sTitle,price,state,ordersid,number,shopid) VALUES ('$userid','$goodsid','".$goods_result['title']."','$fTitle','$sTitle','".$goods_result['goods_price']."',2,'$orders_id','$addnum','".$goods_result['shopid']."')");
		
		// 记录到购物车 end
		if(!mysql_insert_id()){
			mysql_query("ROLLBACK");  
			mysql_query("END");
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '提交订单失败5';
			echo json_encode($result_data_array);
			exit;

		}
		// 更新商品的销量
		$query = mysql_query("update goods set xiaoliang=xiaoliang+".$addnum." where goodsid=".$goodsid);
		if(!$query){
			mysql_query("ROLLBACK");  
			mysql_query("END");
			$result_data_array['code'] =  -100;
			$result_data_array['msg'] = '提交订单失败6';
			echo json_encode($result_data_array);
			exit;

		}
		// 更新商品的销量和库存 end

		// 减少该商品规格的数量
		if($fTitle){
			if ($sTitle) {
				$query = mysql_query("update goodsselect set number=number-".$addnum." where goodsid=".$goodsid." and fTitle='".$fTitle."' and sTitle='".$sTitle."'");
			}else{
				$query = mysql_query("update goodsselect set number=number-".$addnum." where goodsid=".$goodsid." and fTitle='".$fTitle."'");
			}
		}else{
			// 更新商品的库存
			$query = mysql_query("update goods set number=number-".$addnum." where goodsid=".$goodsid);
			if(!$query){
				mysql_query("ROLLBACK");  
				mysql_query("END");
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '提交订单失败6';
				echo json_encode($result_data_array);
				exit;

			}
		}

		mysql_query("COMMIT"); 
		// mysql_query("ROLLBACK");   
		mysql_query("END");

		echo json_encode(array('code'=>200,'msg'=>'下单成功','zongjia'=>$all_order_total_goods_price,'numbers'=>$order_numbers));
	}

	//计算返卷
	function get_rate($goodsid,$totalprice){
		
		$array = calculation_rate($goodsid,$totalprice); 
		//小于一分钱
		if($array[0] < 0.01 & $array[1] > 0){
			$array[0] = 0.01;
		}
		return $array;
	}

	//计算返卷,return array 0 返卷金额，1翻卷比例
	function calculation_rate($goodsid,$totalprice){
		//返卷
		$categroy_sql = 'select categroy.rate from categroy left join goods on categroy.cateid = goods.xilie where goods.goodsid = '.$goodsid;
		$categroy_query = mysql_query($categroy_sql);
		$categroy_array = mysql_fetch_assoc($categroy_query);
		if(!$categroy_array){
			return array(0,$rate);

		}
		//返卷比率
		$categroy_array['rate']+=0;
		$rate = $categroy_array['rate'];
		$fan_juan_price = round($rate * $totalprice)/100;  
		
		return array($fan_juan_price,$rate);
	}
	
	//生成订单
	function generateOrders($orderInfo,$userid,$myaddress,$user_return_volume_price){
		$all_order_total_goods_price = 0;
		mysql_query("BEGIN");
		//多订单购买总的支付单号
		$total_numbers = build_order_no();
		//收货地址
		$address =  $myaddress['province'].",".$myaddress['city'].",".$myaddress['quyu'].",".$myaddress['address'].",".$myaddress['name'].",".$myaddress['tel'];
		//订单状态
		$state = 0;

		foreach ($orderInfo as $shopid => $shop_order_info) {
			//单个订单号
			$order_numbers       = build_order_no();
			
			//订单商品总价
			$totalprice          = $shop_order_info['order_total_price'];
			
			
			//是否购买运费险
			$buyFreightRisk      = $shop_order_info['order_isbuyFreightRisk'];
			//运费险总价
			$freightRisk_price   = $shop_order_info['order_total_freightRisk_price'];
			//快递费总价
			$distribution_fee    = $shop_order_info['order_total_express_price'];
			//留言
			$msg                 = $shop_order_info['msg'];
			//使用的优惠券价值
			$coupon_price        = $shop_order_info['order_coupon_price'];
			//使用的优惠券id
			$coupon_id           = $shop_order_info['order_couponid'];
			//是否使用返卷
			$use_return_volume   = $shop_order_info['order_use_return_volume'];
			//是否使用返卷价值
			$return_volume_price = $shop_order_info['order_return_volume_price'];
			
			
			//发票类型
			$invoice_type        = $shop_order_info['invoice_type'];
			//发票信息数据
			$invoice_data        = $shop_order_info['invoice_data'];
			
			$fan_yong_price      = $shop_order_info['fan_yong_price'];
			$fan_juan_price      = $shop_order_info['fan_juan_price'];
			$ying_jie_price      = $shop_order_info['ying_jie_price'];
			
			$rates               = $shop_order_info['rates'];
			$rate                = $shop_order_info['rate'];
			
			//首单返券使用金额
			$first_coupon_price  = $shop_order_info['first_price'];
			//首单返券id
			$first_couponId      = $shop_order_info['usersFirstId'];
			
			//下单时间
			$xia_dan_datetime    = date("Y-m-d H:i:s");

			//总订单应付金额
			$all_order_total_goods_price = round($all_order_total_goods_price*100 + $distribution_fee*100 + $freightRisk_price*100 + $totalprice*100 - $coupon_price*100 - $return_volume_price*100)/100;
			//end
			
			//单个订单应付金额
			$accounts_payable = round($distribution_fee*100 + $freightRisk_price*100 + $totalprice*100 - $coupon_price*100 - $return_volume_price*100)/100;
			//end
			
			$orders_id = insert_order_data($total_numbers, $order_numbers, $totalprice, $state, $userid, $address, $shopid, 
			$freightRisk_price, $buyFreightRisk, $distribution_fee, $msg, $coupon_price,$coupon_id, $first_couponId, $first_coupon_price, $xia_dan_datetime, $invoice_type,$invoice_data,$return_volume_price,$fan_juan_price,$fan_yong_price,$ying_jie_price,$rate,$rates,$accounts_payable);


			if(!$orders_id){
				mysql_query("ROLLBACK");  
				mysql_query("END");

				$result_data_array['code'] =  -102;
				$result_data_array['msg'] = '下单失败01';
				echo json_encode($result_data_array);
				exit;
			}
			
			foreach ($shop_order_info['goods_list'] as $key => $goods_item) {
				//更新购物车信息
				$update_car_query = mysql_query("update car set ordersid='".$orders_id."',number=".$goods_item['addnum'].",state=7,goodsname='".$goods_item['title']."',price=".$goods_item['goods_price']." where carid = ".$goods_item['carid']." and state=0");
				if(!$update_car_query ){
					mysql_query("ROLLBACK");  
					mysql_query("END");
					$result_data_array['code'] =  -100;
					$result_data_array['msg'] = '提交订单失败2';
					echo json_encode($result_data_array);
					exit;
				}
				//更新销量和库存
				$fTitle = $goods_item['fTitle'];
				$sTitle = $goods_item['sTitle'];
				$addnum = $goods_item['addnum'];
				$goodsid =  $goods_item['goodsid'];
				if($fTitle){
					$srat3 ;
					if($sTitle){
						$srat3 = mysql_query("update goodsselect set number=number-'" . $addnum . "' where goodsid=" . $goodsid . " and fTitle='" . $fTitle . "' and sTitle='" . $sTitle . "'");
					}else{
						$srat3 = mysql_query("update goodsselect set number=number-'" . $addnum . "' where goodsid='" . $goodsid. "' and fTitle='" . $fTitle. "'");
					}
					$srat1 = mysql_query("update goods set xiaoliang=xiaoliang+'" . $addnum . "' where goodsid=" . $goodsid);
					if(!$srat1 || !$srat3){
				    	mysql_query("ROLLBACK");  
						mysql_query("END");
						$result_data_array['code'] =  -100;
						$result_data_array['msg'] = '提交订单失败2';
						echo json_encode($result_data_array);
						exit;
				    }
				}else{
				     $srat1 = mysql_query("update goods set number=number-'". $addnum . "',xiaoliang=xiaoliang+'" . $addnum . "' where goodsid='" . $goodsid. "'");
				     if(!$srat1){
				    	mysql_query("ROLLBACK");  
						mysql_query("END");
						$result_data_array['code'] =  -100;
						$result_data_array['msg'] = '提交订单失败2';
						echo json_encode($result_data_array);
						exit;
				    }
				}
				//更新商品库存和销量
				// $goods_car_query = mysql_query("update ")
				
			}

			//更新优惠券
			if( $coupon_id != 0){
				$update_mycoupon_query = mysql_query('update mycoupon set is_use = 1 where id = '. $coupon_id);
				if(!$update_mycoupon_query ){
					mysql_query("ROLLBACK");  
					mysql_query("END");
					$result_data_array['code'] =  -100;
					$result_data_array['msg'] = '提交订单失败3';
					echo json_encode($result_data_array);
					exit;
				}

			}

			//更新用户返卷金额
			$update_user_return_volume_query = mysql_query('update user set return_volume = '.$user_return_volume_price.' where userid = '.$userid);
			if(!$update_user_return_volume_query ){
				mysql_query("ROLLBACK");
				mysql_query("END");
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '提交订单失败4';
				echo json_encode($result_data_array);
				exit;
			}
		}
		mysql_query("COMMIT"); 
		// mysql_query("ROLLBACK");   
		mysql_query("END");
		echo json_encode(array('code'=>200,'msg'=>'下单成功','zongjia'=>$all_order_total_goods_price,'numbers'=>$total_numbers));
		

	}


	//插入订单数据
	function insert_order_data($total_numbers, $numbers, $totalprice, $state, $userid, $address, $shopid, 
		$freightRisk_price, $buyFreightRisk, $distribution_fee, $msg, $coupon_price,$coupon_id, $first_couponId, $first_coupon_price, $xia_dan_datetime, $invoice_type,$invoice_data,$return_volume_price,$fan_juan_price,$fan_yong_price,$blance_price,$fan_juan_bi_li,$fan_yong_bi_li,$accounts_payable){

		$sql = "insert into goodsorders(total_numbers, numbers, totalprice, state, userid, address, shopid, 
		freightRisk_price, buyFreightRisk, distribution_fee, msg, coupon_price,coupon_id, first_couponId, first_coupon_price, xia_dan_datetime, invoice_type,
		invoice_data,return_volume_price,fan_juan_price,fan_yong_price,blance_price,fan_juan_bi_li,fan_yong_bi_li,type, accounts_payable) values('$total_numbers', '$numbers', $totalprice, $state, $userid, '$address', $shopid, 
		'$freightRisk_price', $buyFreightRisk, $distribution_fee, '$msg', '$coupon_price',$coupon_id, '$first_couponId', $first_coupon_price, '$xia_dan_datetime', $invoice_type,'$invoice_data',$return_volume_price,$fan_juan_price,$fan_yong_price,$blance_price,'$fan_juan_bi_li','$fan_yong_bi_li',0,$accounts_payable)";
		
		$result  = mysql_query($sql);
		$id = mysql_insert_id();
		if($result && $id){
			return $id;
		}
		return 0;
	}


	//获取快递费
	function getTotal_express_price($myaddress,$goods,$addnum){
		$total_freightRisk = 0;
		$sql = mysql_query("select * from fare where `area` like '%".$myaddress[quyu]."%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
	
			$result0 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[city]."%'  AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result1 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result2 = mysql_fetch_assoc($sql);


			$sql = mysql_query("select * from fare where `area` like '%0%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = ".$shopid." and isPay = 0)");
			$result3 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[quyu]."%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result4 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[city]."%'  AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid = ".$goods['muid']." and muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result5 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result6 = mysql_fetch_assoc($sql);

			$sql = mysql_query("select * from fare where `area` like '%0%' and muid = ".$goods['muid']." and  muid in (select id from fareml where shopid = 0 and isPay = 0)");
			$result7 = mysql_fetch_assoc($sql);
			
			if ($result0) {
				$where_area = "AND `area` like '%".$myaddress[quyu]."%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result1) {
				$where_area = "AND `area` like '%".$myaddress[city]."%' AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result2) {
				$where_area = "AND `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result3){
				$where_area = "AND `area` like '%0%' and muid in (select id from fareml where shopid = ".$shopid.")";
			}elseif ($result4) {
				$where_area = "AND `area` like '%".$myaddress[quyu]."%' and muid in (select id from fareml where shopid = 0)";
			}elseif ($result5) {
				$where_area = "AND `area` like '%".$myaddress[city]."%' AND `area` NOT LIKE '%".$myaddress[city]."-%' and muid in (select id from fareml where shopid = 0)";
			}elseif ($result6) {
				$where_area = "AND `area` like '%".$myaddress[province]."%' AND `area` NOT LIKE '%".$myaddress[province]."-%' and muid in (select id from fareml where shopid = 0)";
			}else{
				$where_area = "AND `area` like '%0%' and muid in (select id from fareml where shopid = 0)";
			}
			// 运费条件 end
			

			// 计算运费 
				
			$sql = mysql_query("select * from fare  WHERE muid = ".$goods['muid']."  ".$where_area);
			$fare_row  = mysql_fetch_assoc($sql);
			if($fare_row){
				$fare = $fare_row['fare'];
				$addfare = $fare_row['addfare'];
				$begincount = $fare_row['begincount'];
				$distance_count = $fare_row['distance_count'];

				//加上初始件数运费
				
				$fare+=0;
				$begincount+=0;
				$distance_count+=0;
				$total_freightRisk += $fare;
				//购买的件数大于初始件数

				if($addnum > $begincount){
					//计算超过件数
					$distance_num = $addnum - $begincount;
					//计算需要加多少次，向下取整
					$addfare_count = floor($distance_num/$distance_count);

					$total_freightRisk += $addfare_count*$addfare;
				}
			}

			$istuangou = $goods['istuangou'];
			
			if($istuangou == 1){
                 $sql1 = mysql_query("select * from buygroup  WHERE buygroup_id = ".$goods['buygroup_id']."");
			     $tuan_row  = mysql_fetch_assoc($sql1);
			     $bei = $addnum/$tuan_row['mcount'];
			     $total_freightRisk = $bei*$tuan_row['yunfare'];
			}
			return $total_freightRisk;
				
			// 计算运费 end
	}

	//获取运费险
	function getTotal_Freight($addnum){
		// 计算运费险
		$query = mysql_query("select * from freightrisk");
		$freightRisk = 0;
		while ($row = mysql_fetch_assoc($query)) {
			if ($addnum >= $row['goodsNum']) {
				$freightRisk = $row['freightRisk'];
			}
		}
		return $freightRisk+0;
	}

	//获取优惠券金额
	//couponid 优惠券id
	//total_price 一个商家订单的总价格
	//userid 用户id
	function get_coupon_price($couponid,$total_price,$userid){
		//查询优惠券信息
		$now_date = date('Y-m-d H:i:s');
		if($couponid != 0){
			$coupon_query = mysql_query('select coupon.price from coupon left join mycoupon on coupon.couponid = mycoupon.couponid where coupon.couponid = '.$couponid.' and coupon.top_price < '.$total_price.' and coupon.startdate < "'.$now_date.'" and coupon.enddate > "'.$now_date.'" and mycoupon.is_use = 0');
			$coupon_result = mysql_fetch_assoc($coupon_query);
			if(!$coupon_result){
				$result_data_array['code'] =  -100;
				$result_data_array['msg'] = '优惠券异常';
				echo json_encode($result_data_array);
				exit;
			}

			return $coupon_result['price']+0;
		}

		return 0;
			
	}

	/**
	 * [获取首单返券金额]
	 * @Author    Axing
	 * @DateTime  2017-07-10
	 * @version   [1.0]
	 * @param     [type] $usersFirstId	[首单返券id]
	 * @param     [type] $goods_result	[商品总额]
	 * @return    [type] $firstConpon	[首单返券减免金额]
	 */
	function get_first_coupon ($usersFirstId,$goods_result) {
		
		if($usersFirstId) {
			$sql = "SELECT * FROM orders_users_first WHERE id = " . $usersFirstId;
			$query = mysql_query($sql);
			$usersFirst = mysql_fetch_array($query);

			$firstConpon = $goods_result*($usersFirst['first_cate_use']*0.01);
			if($usersFirst['lastAmount'] < $firstConpon && $usersFirst['lastAmount'] != 0) {
				$firstConpon = $usersFirst['lastAmount'];
			}

			if($usersFirst['lastAmount'] == null) {
				$usersFirst['lastAmount'] = $usersFirst['amount']-$firstConpon;
			} else {
				$usersFirst['lastAmount'] = $usersFirst['lastAmount']-$firstConpon;
			}

			$sql = "UPDATE orders_users_first set lastAmount = " . $usersFirst['lastAmount'] ." where id = " . $usersFirstId;
			$query = mysql_query($sql);
			return $firstConpon;
		} else {
			return 0;
		}
	}

	function get_car_fPrice ($goodsid, $price, $usersFirstId, $num, $userid) {
			//$userid = 2585;
			/*$sql = "SELECT  a.first_cate_use, a.lastAmount, a.amount FROM orders_users_first AS a LEFT JOIN orders_first AS b ON b.id = a.firstid LEFT JOIN goods AS c ON c.xilie = b.cateid WHERE c.goodsid = " . $goodsid . " AND uid = " . $userid . " AND a.id = " . $usersFirstId;*/

			$sql = "SELECT  a.first_cate_use, a.lastAmount, a.amount FROM orders_users_first AS a LEFT JOIN orders_first AS b ON b.id = a.firstid WHERE  uid = ".$userid." AND a.id = ".$usersFirstId."";
			$row = mysql_fetch_assoc(mysql_query($sql));
         
			$price = $price*$num*($row['first_cate_use']*0.01);
			if($row['lastAmount'] < $price && $row['lastAmount'] != 0) {
				$price = $row['lastAmount'];
			}

			if($price != 0) {
				if($row['lastAmount'] == null) {
					$row['lastAmount'] = $row['amount']-$price;
				} else {
					$row['lastAmount'] = $row['lastAmount']-$price;
				}
			} 
			$sql = "UPDATE orders_users_first set lastAmount = " . $row['lastAmount'] ." where id = " . $usersFirstId;
			$query = mysql_query($sql);

			return $price;
	}
 ?>		
